package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    @Autowired
    private IBedService bedService;

    @Autowired
    private IElderService elderService;



    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

//    @Override
    public AjaxResult checkInApply1(CheckInApplyDto checkInApplyDto) {
        //验证老人是否已入住
        CheckIn elder = checkInService.lambdaQuery()
                .eq(CheckIn::getId, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder!= null && elder.getStatus() == 1){
            throw new RuntimeException("老人已入住");
        }
        //更新床位状态为已入住
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        Bed dbBed = bedService.getById(bed);
        if (dbBed == null){
            throw new RuntimeException("床位不存在");
        }
        //新增或更新老人
        Elder oldElder =BeanUtil.toBean(checkInApplyDto.getCheckInElderDto(),Elder.class);
        oldElder.setStatus(1);
        oldElder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        oldElder.setBedNumber(dbBed.getBedNumber());
        if (elder != null){
            oldElder.setId(elder.getId());
        }
        elderService.saveOrUpdate(oldElder);

        //新增签约办理
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(),Contract.class);
        contract.setElderId(oldElder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(checkInApplyDto.getCheckInElderDto().getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(),CheckIn.class);
        checkIn.setElderId(oldElder.getId());
        checkIn.setElderName(checkInApplyDto.getCheckInElderDto().getName());
        checkIn.setIdCardNo(checkInApplyDto.getCheckInElderDto().getIdCardNo());
        checkIn.setBedNumber(oldElder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig hc = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        hc.setCheckInId(checkIn.getId());
        checkInConfigService.save(hc);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult checkInApply(CheckInApplyDto checkInApplyDto) {
        //验证老人是否已入住
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()).one();
        elder.setStatus(1);
        elder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        elder.setBedNumber(bedService.selectBedById(elder.getBedId()).getBedNumber());
        if (elder != null && elder.getStatus() == 1){
            throw new RuntimeException("老人已入住");
        }
        //更新床位状态为已入住
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        Bed daBed = bedService.getById(bed);
        if (daBed == null){
            throw new RuntimeException("床位不存在");
        }
        //新增或更新老人
        if(elder != null){
            elder.setId(elder.getId());
        }
        elderService.saveOrUpdate(elder);

        //新增签约办理
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(),Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(checkInApplyDto.getCheckInElderDto().getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(),CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(checkInApplyDto.getCheckInElderDto().getName());
        checkIn.setIdCardNo(checkInApplyDto.getCheckInElderDto().getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig hc = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        hc.setCheckInId(checkIn.getId());
        checkInConfigService.save(hc);
        return AjaxResult.success();
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInService.selectCheckInById(id);
        //查询老人信息
        Elder elder = elderService.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder,CheckInElderVo.class);
        //查询合同
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId,checkIn.getElderId()).one();
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId,checkIn.getId()).one();
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig,CheckInConfigVo.class);
        //转换家属列表
        List<ElderFamilyVo> list = JSONUtil.toList(elder.getRemark(), ElderFamilyVo.class);
        //整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(list);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
